package com.mtf.chatdemo.util;

import com.mtf.chatdemo.websocket.MyWebSocket;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class WebSocketUtil {
    //获取一个Map集合中的所有的key
    public static Set<String> getAllKeyFromMap(Map<String, MyWebSocket> map){
        Set<String> keySet = map.keySet();
        return keySet;
    }

    //遍历所有的key（也就是在线的用户名，根据这些用户名来给他们发送“广播消息”）
    //某个用户成功登录，系统发送广播消息：某某用户上线啦！
    public static void sendBroadCastMessage(Map<String,MyWebSocket> map,String message) throws IOException {
        Set<String> set = getAllKeyFromMap(map);
        for (String name : set) {
            MyWebSocket myWebSocket = map.get(name);
            myWebSocket.session.getBasicRemote().sendText(message);
        }
    }

    //某个用户给某个用户发送消息（1对1）
    public static void sendMessageOneToOne(String toUserName,String message,Map<String,MyWebSocket> map){
        MyWebSocket myWebSocket = map.get(toUserName);
        try {
            myWebSocket.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
